package com.imddy.tweb.util;

import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;

public class HttpPoolUtils {

	private static Log log = LogFactory.getLog(HttpPoolUtils.class);

	public static final String UTF8 = "UTF-8";
	public static volatile boolean isClosed = false;

	public static final int maxTotalPool = 150;
	public static final int maxPerRoute = 100;
	public static final int MAX_TIMEOUT = 30000;
	public static final int RequestTimeout = 5000;

	private static RequestConfig requestConfig;
	private static HttpClientBuilder httpClientBuilder;
	private static PoolingHttpClientConnectionManager poolConnManager;

	static {
		// 设置连接池
		poolConnManager = new PoolingHttpClientConnectionManager();
		poolConnManager.setMaxTotal(maxTotalPool);// 设置连接池大小
		poolConnManager.setDefaultMaxPerRoute(maxPerRoute);

		// RequestConfig.Builder configBuilder = RequestConfig.custom();
		RequestConfig.Builder configBuilder = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT);
		// 设置连接超时
		configBuilder.setConnectTimeout(MAX_TIMEOUT);
		// 设置读取超时
		configBuilder.setSocketTimeout(MAX_TIMEOUT);
		// 设置从连接池获取连接实例的超时
		configBuilder.setConnectionRequestTimeout(RequestTimeout);
		// 在提交请求之前 测试连接是否可用
		// configBuilder.setStaleConnectionCheckEnabled(true);
		requestConfig = configBuilder.build();
		//
		httpClientBuilder = HttpClients.custom()
				.setConnectionManager(poolConnManager)
				.setDefaultRequestConfig(requestConfig);
		System.out.println(">>>>>>>>>>> PoolingHttpClientConnectionManager初始化成功 >>>>>>>>>>>");
	}

	/**
	 * 获取HttpClient客户端
	 * 
	 * @return httpClient
	 */
	public static CloseableHttpClient getClient() {
		CloseableHttpClient httpClient = HttpClients.custom()
				.setConnectionManager(poolConnManager)
				.setDefaultRequestConfig(requestConfig)
				.build();
		if (null == httpClient) {
			httpClient = HttpClients.createDefault();
		}
		
		return httpClient;
	}

	/**
     * 从http连接池里获取客户端实例
     * @return httpClient
     */
    public static CloseableHttpClient getHttpClient() {   
        CloseableHttpClient httpClient = httpClientBuilder.build(); 
        if( null == httpClient ){
        	log.info("---------HttpClients.createDefault()---------");
        	httpClient = HttpClients.createDefault();
        }
        
        return httpClient;  
    }
    
    
    public static CloseableHttpClient getHttpsClient() {
    	CloseableHttpClient httpsClient = httpClientBuilder.build(); 
        if( null == httpsClient ){
        	log.info("---------HttpClients.createDefault()---------");
        	httpsClient = HttpClients.createDefault();
        }
        
        return httpsClient;  
    }
    
    
    /**
     * 关闭连接池资源
     */
    public static void closePool() {
    	if( !isClosed ){
    		isClosed = true;
    		poolConnManager.close();
    	}
    }
	
	
    
    
    public void test2() {
    	 RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder.<ConnectionSocketFactory>create();
    		ConnectionSocketFactory plainSF = new PlainConnectionSocketFactory();
    		registryBuilder.register("http", plainSF);
    		//指定信任密钥存储对象和连接套接字工厂
    		try {
    			KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    			//信任任何链接
    			TrustStrategy anyTrustStrategy = new TrustStrategy() {
    				@Override
    				public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
    					return true;
    				}

    			};
    			SSLContext sslContext = SSLContexts.custom().useTLS().loadTrustMaterial(trustStore, anyTrustStrategy).build();
    			LayeredConnectionSocketFactory sslSF = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    			registryBuilder.register("https", sslSF);
    		} catch (Exception e) {
    			log.error("register https failed",e);
    		}
    		Registry<ConnectionSocketFactory> registry = registryBuilder.build();
    		
    }
   
	
	
	public static void main(String[] args) {

	}

}
